package com.fenghuajueli.libbasecoreui.upload.xiaomi

import android.app.Application
import android.os.Build
import android.util.Log
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.fenghuajueli.libbasecoreui.BaseApplication
import com.fenghuajueli.libbasecoreui.upload.BaseUpload
import com.fenghuajueli.libbasecoreui.upload.Channel
import com.fenghuajueli.libbasecoreui.utils.MmkvUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class XiaomiUploadUtils : BaseUpload() {

    companion object {
        @JvmStatic
        val instance: XiaomiUploadUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            XiaomiUploadUtils()
        }
    }

    /**
     * 打开应用时检查
     * 首次安装
     * 次日留存
     * @param lifecycleOwner
     * @param application
     */
    @Deprecated("统一在MyApplication调用", replaceWith = ReplaceWith("openAction(application: Application)"))
    fun openAction(lifecycleOwner: LifecycleOwner, application: Application) {
        lifecycleOwner.action(Channel.XIAOMI) {
            if (checkIsFirstInstall(application)) {
                MmkvUtils.save(FIRST_LAUNCH, false)
                LogUtils.d("firstInstallAction: 首次安装启动")
                uploadActiveData(application, XmDataType.APP_ACTIVE_NEW)
            } else if (checkSeconddayRetention()) {
                LogUtils.d("firstInstallAction: 次留")
                uploadActiveData(application, XmDataType.APP_RETENTION)
            }
        }
    }

    fun openAction(application: Application) {
        appScope.launch {
            action(Channel.XIAOMI) {
                if (checkIsFirstInstall(application)) {
                    MmkvUtils.save(FIRST_LAUNCH, false)
                    LogUtils.d("firstInstallAction: 首次安装启动")
                    uploadActiveData(application, XmDataType.APP_ACTIVE_NEW)
                } else if (checkSeconddayRetention()) {
                    LogUtils.d("firstInstallAction: 次留")
                    uploadActiveData(application, XmDataType.APP_RETENTION)
                }
            }
        }
    }

    /**
     * 注册
     * 注册完3分钟内算新注册用户
     * @param needCheck 一键登录、微信登录需要传true
     * @param application
     */
    @Deprecated("统一在MyApplication调用", replaceWith = ReplaceWith("registerAction(application: Application)"))
    fun registerAction(
        lifecycleOwner: LifecycleOwner,
        application: Application,
        needCheck: Boolean = false
    ) {
        lifecycleOwner.action(Channel.XIAOMI) {
            if (needCheck) {
                if (checkIsRegister()) {
                    uploadActiveData(application, XmDataType.APP_REGISTER)
                }
            } else {
                uploadActiveData(application, XmDataType.APP_REGISTER)
            }
        }
    }

    fun registerAction(application: Application) {
        appScope.launch {
            action(Channel.XIAOMI) {
                uploadActiveData(application, XmDataType.APP_REGISTER)
            }
        }
    }


    /**
     * 付费
     * 7天内付费才上传
     * @param lifecycleOwner
     * @param application
     * @param payAmount
     */
    @Deprecated("统一在MyApplication调用", replaceWith = ReplaceWith("payAction(application: Application, payAmount: Double)"))
    fun payAction(lifecycleOwner: LifecycleOwner, application: Application, payAmount: Double) {
        lifecycleOwner.action(Channel.XIAOMI) {
            if (checkPayWithinSevendays()) {
                uploadActiveData(application, XmDataType.APP_PAY, (payAmount * 100).toLong())
            }
        }
    }

    fun payAction(application: Application, payAmount: Double) {
        appScope.launch {
            action(Channel.XIAOMI) {
                if (checkPayWithinSevendays()) {
                    uploadActiveData(application, XmDataType.APP_PAY, (payAmount * 100).toLong())
                }
            }
        }
    }

    /**
     * vivo转化数据同步接口
     *
     * @param dataType
     * @param payAmount
     */
    private suspend fun uploadActiveData(
        application: Application,
        dataType: XmDataType,
        payAmount: Long? = null,
        keyActionType: XmKeyActionType? = null,
    ) {
        application.uploadActiveData(Channel.XIAOMI) {
            val contentsMap = hashMapOf<String, Any>()
            contentsMap.apply {
                //oaid
                contentsMap["oaid"] = oaid ?: ""
                //转化类型
                contentsMap["conv_type"] = dataType.name
                //事件发生的系统时间戳
                contentsMap["conv_time"] = System.currentTimeMillis()
                //付费金额
                payAmount?.let { contentsMap["conv_weight"] = it }
                //IP地址
                contentsMap["client_ip"] = NetworkUtils.getIPAddress(true)
                //客户端ua
                contentsMap["ua"] = System.getProperty("http.agent") ?: ""

                //包名
                contentsMap["pkgName"] = application.packageName
                //商标
                contentsMap["brand"] = Build.BRAND
                //厂商
                contentsMap["manufacturer"] = Build.MANUFACTURER
                //机型
                contentsMap["model"] = Build.MODEL
                keyActionType?.let {
                    contentsMap["key_action_type"] = keyActionType.code
                    contentsMap["key_action_threshold"] = keyActionType.threshold
                    contentsMap["key_action_reach"] = 1
                }
            }

            GsonUtils.toJson(contentsMap)
        }
    }


    /**
     * 关键行为归因
     */
    fun keyAction(lifecycleOwner: LifecycleOwner, type: XmKeyActionType) {
        val appAddictionUploaded = MmkvUtils.get(type.name, false)
        if (appAddictionUploaded) {
            LogUtils.d("BaseUpload", "已上传过数据")
            return
        }
        when (type) {
            XmKeyActionType.AppOpenTime -> appOpenTimeAction(lifecycleOwner, type)
            XmKeyActionType.AppTimeUsage -> appTimeUsageAction(lifecycleOwner, type)
        }
    }

    private fun appTimeUsageAction(lifecycleOwner: LifecycleOwner, type: XmKeyActionType) {
        val application = BaseApplication.getApplication()
        lifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
            action(Channel.XIAOMI) {
                val packageManager = application.packageManager
                val packageInfo = packageManager.getPackageInfo(application.packageName, 0)
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    val firstInstallTime = packageInfo.firstInstallTime
                    val now = System.currentTimeMillis()
                    // 使用时间大于600秒
                    if (now - firstInstallTime >= 600 * 1000) {
                        uploadActiveData(
                            application,
                            XmDataType.APP_ADDICTION,
                            keyActionType = type
                        )
                        // 只上传一次
                        MmkvUtils.save(type.name, true)
                    }
                }
            }
        }
    }

    private fun appOpenTimeAction(lifecycleOwner: LifecycleOwner, type: XmKeyActionType) {
        val application = BaseApplication.getApplication()
        lifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
            action(Channel.XIAOMI) {

                val openTime = MmkvUtils.get("APP_TIME_OPENED", 0) + 1
                MmkvUtils.save("APP_TIME_OPENED", openTime)
                if (openTime >= 5) {
                    uploadActiveData(application, XmDataType.APP_ADDICTION, keyActionType = type)
                    MmkvUtils.save(type.name, true)
                }
            }
        }
    }

}
